package cn.simple.http;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HttpFactory {

    public static HttpRequest parse(String requestExpression) {
        if(requestExpression == null) {
            return null;
        }
        HttpRequest request = null;
        String regexp = "(?<httpMethod>GET|POST)\\s+(?<httpUrl>\\S+)(?<headers>(\n.+)+)?(?<httpContent>\n\n.+)?";
        Pattern pattern = Pattern.compile(regexp, Pattern.DOTALL);
        Matcher matcher = pattern.matcher(requestExpression);
        if (matcher.find()) {
            String httpMethod = matcher.group("httpMethod");
            String httpUrl = matcher.group("httpUrl");
            request = new HttpRequest(httpMethod, httpUrl);
            String headers = matcher.group("headers");
            String httpContent = matcher.group("httpContent");
            request.setContent(httpContent);

            if (headers != null) {
                Matcher headMatcher = Pattern.compile("(?<key>.+):\\s*(?<value>.+)").matcher(headers);
                while (headMatcher.find()) {
                    String key = headMatcher.group("key");
                    String value = headMatcher.group("value");
                    request.addHeader(key, value);
                }
            }
        }
        return request;
    }
}
